local args = ngx.req.get_uri_args()

if nil == args.act_id then
    ngx.say('{"code":10000,"message":"act_id不能为空"}')
    return
end

local act_id = args.act_id
local redis_client = require "lib.redis"
local redis = redis_client:new()

local total, err = redis:hlen('scores:'..act_id)

if err ~= nil then
    ngx.log(ngx.ERR, 'connect redis faild:', err)
    ngx.say('{"code":10000,"message":"服务器内部错误","error":"', err,'"}')
    return
end

local per_page = tonumber(args.per) or 20
local page = tonumber(args.page) or 1

if total == 0 then
    ngx.say('{"code":200,"message":"success","data":{"total":0',
        ',"per_page":', per_page,',"page":', page, ',"items":[],"scores":[]}}'
    )
    return
end

local offset = (page - 1) * per_page

if offset < 0 then
    offset = 0
end

-- 根据投票数查出id和对应的票数
local rank, err = redis:zrevrangebyscore('ranking:'..act_id, '+inf', 0, 'WITHSCORES', 'LIMIT', offset, per_page)

if err ~= nil then
    ngx.log(ngx.ERR, 'connect redis faild:', err)
    ngx.say('{"code":10000,"message":"服务器内部错误","error":"', err,'"}')
    return
end

if rank == nil then
    ngx.say('{"code":200,"message":"success","data":{"total":', total,
        ',"per_page":', per_page,',"page":', page, ',"items":[],"scores":[]}}'
    )
    return
end

local item_keys, scores = {}, {}

-- 将id和票数分别组装，并将id组合成取item得key
for i, value in pairs(rank) do
    if i % 2 == 0 then
        --票数
        table.insert(scores, value)
    else
        --id
        table.insert(item_keys, '_item:'..act_id..":"..value)
    end
end

local _items, err = redis:mget(unpack(item_keys))

if err ~= nil then
    ngx.log(ngx.ERR, 'connect redis faild:', err)
    ngx.say('{"code":10000,"message":"服务器内部错误","error":"', err,'"}')
    return
end

if nil == _items then
    ngx.say('{"code":200,"message":"success","data":{"total":', total,
        ',"per_page":', per_page,',"page":', page, ',"items":[],"scores":[]}}'
    )
    return
end

local items = {}

for of, item in ipairs(_items) do
    if item == ngx.null then
        table.remove(scores, of)
    else
        table.insert(items, item)
    end
end

ngx.say('{"code":200,"message":"success","data":{"total":', total,
    ',"per_page":', per_page,
    ',"page":', page,
    ',"items":[', table.concat(items, ','), '],"scores":[', table.concat(scores, ','), ']}}'
)
